// import Vue from 'vue'
let Vue = null;
// import RouterView from './RouterView.vue'
// import RouterView from './RouterLink.vue'
class HistoryRoute{
	constructor(){
		this.current = null;

		// Object.defineProperty(this,'current',{
		// 	get(){
		// 		return _current
		// 	},
		// 	set:(val)=>{
		// 		_current=val;
		// 		console.log("set")
		// 		console.log(this.vm)
		// 		this.vm.$forceUpdate()
		// 	}
		// })
	}
}
class LcRouter{
// 传入模式、路由设置
	constructor(options){
		// 根据是否有配置路由模式，如果有配置就是用配置的模式，没有的话，就模式是hash
		this.mode = options.mode || "hash";
		this.routes = options.routes||[] ;//传入路由的配置的数组列表
		// 根据路由数组生成路由映射
		this.routesMap = this.createMap(this.routes)
		this.history = new HistoryRoute();
		this.init()

	}
	init(){
		if(this.mode=="hash"){
			// 先判断用户打开时有没有hash值，没有的话就跳转至#/
			location.hash?"":location.hash = "/"
			window.addEventListener('load',()=>{
				// #/about,将路径的#去掉
				this.history.current = location.hash.slice(1)
			});
			window.addEventListener('hashchange',()=>{
				this.history.current = location.hash.slice(1)
			})
		}else{
			location.pathname?"":location.pathname = "/"
			window.addEventListener('load',()=>{
				this.history.current = location.pathname
			})
			window.addEventListener('popstate',()=>{
				this.history.current = location.pathname
			})
		}
	}
	// 创建路由映射
	// [{path:"/abc",com:comobj}]
	// {"/abc":comobj}
	createMap(routes){
		return routes.reduce((pre,current)=>{
			pre[current.path] = current.component;
			return pre
		},{})
	}
	// install(v){
	// 	Vue.component('router-view',RouterView)
	// 	Vue.component('router-link',RouterLink)
	// }
}


LcRouter.install = function(v){
	// this.$router
	// this.$route
	// 让组件都拥有什么方法，那么可以使用全局mixin
	Vue = v
	Vue.mixin({
		beforeCreate(){
			if(this.$options&& this.$options.router){
				// 如果是根组件
				this._root = this;
				console.log(this)
				console.log(this.$options.router)
				this._router = this.$options.router;
				// this.$root._router.history.vm =this.$root
				Vue.util.defineReactive(this,"history",this._router.history)
			}else{
				this._root = this.$parent && this.$parent._root;

			}
			Object.defineProperty(this,"$router",{
				get(){
					return this._root._rooter
				}
			})
			Object.defineProperty(this,'$route',{
				get(){
					return this._root._router.history.current;
				}
			})
		}
	})


	Vue.component('router-link',{
		props:{
			to:String
		},
		render(h){
			// 根据我们上面设置的结构，获取路径的模式
			console.log(this._self._root.router)
			let mode = this._self._root._router.mode;
			let to = mode === 'hash'?"#"+this.to:this.to;
			return h('a',{
				attrs:{href:to}
			},this.$slots.default)
		}
	})

	Vue.component('router-view',{
		render(h){
			console.log(this._self._root._router.history)
			let current = this._self._root._router.history.current;
			let routeMap = this._self._root._router.routesMap;
			console.log(current)
			console.log(routeMap)
			
			return h(routeMap[current])
		}
	})
}

export default LcRouter